<?php
class Ajax_login extends MY_Controller {
    function __construct() {
        parent::__construct();
    }
    
    function login_by_cookie() {
    	if ($_COOKIE[sha1(COOKIE_USER_AUTH)]) {
    		if ($data = $this->_check_cookie(sha1(COOKIE_USER_AUTH), $_COOKIE[sha1(COOKIE_USER_AUTH)])) {
    			$this->_allocate_user_auth_session($data);
    			$this->output->set_output('succeed');
    		} else {
    			return FALSE;
    		}
    	} else {
    		return FALSE;
    	}
    }
    
    function index() {
    	$name = $this->input->post("username");
    	$email = $this->input->post("email");
        $password = $this->input->post("password");
        $is_remember = ($this->input->post("is_remember") == 'true') ? TRUE : FALSE;
        
        //先判断用户的登录方式
    	if (isset($_POST['username'])) {
    		$validate_data['name'] = $name;
    		if (!$this->_ajax_validate($validate_data)) { return ; }
    	} elseif (isset($_POST['email'])) {
    		$validate_data['email'] = $email;
    		if (!$this->_ajax_validate($validate_data)) { return ; }
    	}
    	
     	$validate_data['password'] = $password;
    	if (!$this->_ajax_validate($validate_data)) { return ; }
    	
        $this->load->model('user_model', '', TRUE);
        
        if (isset($_POST['username'])) {
        	$data = $this->user_model->get_user_by_name_login($name);
        } elseif (isset($_POST['email'])) {
        	$data = $this->user_model->get_user_by_email_login($email);
        }
        
        if ($data) {
            if ($password != $data['password']) {
                $this->output->set_output(json_encode('password_error'));
            } else {
            	switch ($is_remember) {
            		case TRUE:
            			$update_value['id'] = $data['id'];
						$update_value['username'] = $name;
						$this->_update_cookie(COOKIE_USER_AUTH, $update_value);
            			break;
            		case FALSE:
            			$this->_update_cookie(COOKIE_USER_AUTH, '');
            			break;
            	}
            	
                $this->_allocate_user_auth_session($data);
                $this->output->set_output(json_encode('succeed'));
            }
        } else {
	        if (isset($_POST['username'])) {
	        	$this->output->set_output(json_encode('username_error'));
	        } elseif (isset($_POST['email'])) {
	        	$this->output->set_output(json_encode('email_error'));
	        }
        }
    }
    
	function logout() {
		$this->session->sess_destroy();
		session_destroy();
		
		setcookie(sha1(COOKIE_USER_AUTH), 'DELETED!', time(), '/');
		$this->output->set_output('logout_succeed');
	}
}